package util

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/rand"
	"crypto/rsa"
	"math/big"
)

// RSA 私钥进行数字签名
func SignRSA(plainText []byte, fileName string, hash crypto.Hash) []byte {
	//获取私钥
	privateKey := RSAFromFileGetPrivateKey(fileName)
	//计算哈希值 否则 panic: crypto/rsa: input must be hashed message
	hashed := Sha256SumBytes(plainText)
	//签名
	signPKCS1v15, err := rsa.SignPKCS1v15(rand.Reader, privateKey, hash, hashed)
	if err != nil {
		panic(err)
	}
	return signPKCS1v15
}

// RSA 公钥验证签名
func VerifySignRSA(plainText, signPKCS1v15 []byte, fileName string, hash crypto.Hash) bool {
	//获取公钥
	publicKey := RSAFromFileGetPublicKey(fileName)
	//计算哈希值
	hashed := Sha256SumBytes(plainText)
	//验证签名
	err := rsa.VerifyPKCS1v15(publicKey, hash, hashed, signPKCS1v15)
	if err != nil {
		return false
	}
	return true
}

// ECDRSA 私钥进行数字签名
func SignECDRSA(plainText []byte, fileName string) (rText, sText []byte) {
	//获取私钥
	privateKey := ECDSAFromFileGetPrivateKey(fileName)
	//计算哈希值 否则 panic: crypto/rsa: input must be hashed message
	hashed := Sha256SumBytes(plainText)
	//签名
	r, s, err := ecdsa.Sign(rand.Reader, privateKey, hashed)
	if err != nil {
		panic(err)
	}
	rText, err = r.MarshalText()
	if err != nil {
		panic(err)
	}
	sText, err = s.MarshalText()
	if err != nil {
		panic(err)
	}
	return
}

// RSA 公钥验证签名
func VerifySignECDRSA(plainText, rText, sText []byte, fileName string) bool {
	//获取公钥
	publicKey := ECDSAFromFileGetPublicKey(fileName)
	//计算哈希值
	hashed := Sha256SumBytes(plainText)
	//验证签名
	var r, s big.Int
	r.UnmarshalText(rText)
	s.UnmarshalText(sText)
	return ecdsa.Verify(publicKey, hashed, &r, &s)
}
